/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-05-19 15:21:29
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message } from 'antd';
import { ADD_LEVEL_BY_ID, SET_ADD_TRANSFER_VISIBLE, SET_SELECT_KEYS } from '../constants';
import { LevelLayoutReducer } from '../reducers/LevelLayoutReducer';
import { fetchLevelByATId } from '@/api/archivesType';

const initialState = {
  fondsList: [],
  ATList: [],
  levelList: [],
  // 层级tab列表
  tabList: [],
  // 当前全宗OBJ
  currentFond: {},
  // 当前档案类型ID
  currentAt: 0,
  // 当前级别ID
  currentLevel: '1',
  // 各层级选中的keys
  levelSelectKeys: {},

  // -------- dialogs --------
  // 添加移交单弹窗可视状态
  AddTransferVisible: false
};

const LevelLayoutContext = createContext();

const LevelLayoutContextProvider = (props) => {
  const [state, dispatch] = useReducer(LevelLayoutReducer, initialState);

  const actions = {
    /**
     * @description: 获取档案类型下所有层级
     * @param {number} id
     */
    async fetchATLevel(id) {
      const res = await fetchLevelByATId(id);
      const { data } = res;
      dispatch({ type: ADD_LEVEL_BY_ID, data, id });
    },

    /**
     * @description: 返回选定层级选中的keys
     * @param {*} level 选定的层级
     * @return {*}
     */
    getSelectedKeys(level) {
      return state.levelSelectKeys[level] || [];
    },

    /**
     * @description: 保存表格中的keys
     * @param {number} level 当前层级
     * @param {Key[]} keys 选中的keys
     */
    setLevelSelectKey(level) {
      return (keys) => {
        dispatch({ type: SET_SELECT_KEYS, level, keys });
      };
    },

    // -------- dialogs --------
    /**
     * @description: 打开移交弹窗方法
     * @param {*} isHeight 是否最高层级
     */
    showAddTransfer(isHeight) {
      if (isHeight) {
        dispatch({ type: SET_ADD_TRANSFER_VISIBLE, visible: true });
      } else {
        message.warn('当前层级不可移交');
      }
    },

    /**
     * @description: 关闭移交弹窗
     */
    closeAddTransfer() {
      dispatch({ type: SET_ADD_TRANSFER_VISIBLE, visible: false });
    }
  };

  useEffect(() => {}, []);

  return (
    <LevelLayoutContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </LevelLayoutContext.Provider>
  );
};

export const useLevelLayoutContext = () => {
  return useContext(LevelLayoutContext);
};

export { LevelLayoutContext, LevelLayoutContextProvider };
